﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using Ventuz.OSC;
using System.Collections;

class OSCUnityExample : MonoBehaviour
{
    bool initialized = false;
    UdpReader oscReader;
    public string OSCPath = "/";

    void Start()
    {
        this.gameObject.name = this.gameObject.name + " moved by OSC";
        oscReader = new UdpReader(7000);
        initialized = true;
    }

    void FixedUpdate()
    {
        // Wait for initialization
        if (!initialized) return;
        ParseMessages();
    }

    void ParseMessages()
    {
        // Loop until failure
        while (true)
        {
            // Recieve message from Stack
            OscMessage message = oscReader.Receive();

            // Return if there are no more messages available
            if (message == null) return;
            OscBundle bundle = message as OscBundle;
            if (bundle == null) return;
            
            // Enumerate over all elements
            IEnumerator e = bundle.Elements.GetEnumerator();
            while (e.MoveNext())
            {
                // Check if element matches OSC path of this gameObject
                OscElement el = e.Current as OscElement;
                if (el.Match(OSCPath))
                {
                    Move(bundle.DateTime, el.Args);
                }
            }
        }
    }

    private void Move(DateTime dateTime, object[] p)
    {
        Vector3 v = transform.position;
        if (p.Length >= 2)
        {
            // the object has to be cast to double first, before it can be cast to float
            v.x = (float)(double)p[0]; 
            v.y = (float)(double)p[1];
        }
        if (p.Length >= 3)
        {
            v.z = (float)(double)p[2];
        }
        transform.position = v;
    }
}

